<template>
  <div class="content">
    <div class="header-card">
      <div style="margin-bottom: 5px;">
        <el-button size="mini" type="primary" @click="submit">{{ $t('btn.save') }}</el-button>
      </div>
      <div class="organization">
        <el-form
          ref="nameRef"
          label-width="100px"
          size="mini"
          :model="organization"
          :rules="nameRules"
        >
          <el-form-item :label="$t('market.custname')" prop="fname">
            <el-input
              v-model="organization.fname"
              class="input-width"
            />
          </el-form-item>
          <el-form-item :label="$t('market.customerNo')" prop="fcode">
            <el-input
              v-model="organization.fcode"
              class="input-width"
              disabled
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div>
      <jc-title :title1="$t('market.info')" />
      <div class="basic-information">
        <el-form
          ref="basicRef"
          label-width="100px"
          size="mini"
          :model="basic"
          class="spacing"
          :rules="basicRules"
        >
          <el-form-item :label="$t('market.country')" prop="fcountry">
            <el-input
              v-model="basic.fcountryName"
              class="input-width"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="openCountry=true"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.website')" prop="fwebsite">
            <el-input
              v-model="basic.fwebsite"
              class="input-width"
            />
          </el-form-item>
          <el-form-item :label="$t('market.addressBook')" prop="faddress" style="height: 50px;">
            <el-input
              v-model="basic.faddress"
              class="input-width"
              type="textarea"
            >
              <i slot="suffix" class="el-input__icon el-icon-search" />
            </el-input>
          </el-form-item>
        </el-form>
        <el-form
          ref="callRef"
          label-width="100px"
          size="mini"
          :model="administration"
          class="spacing"
          :rules="adminRules"
        >
          <el-form-item :label="$t('market.ftel')" prop="ftel">
            <el-input
              v-model="administration.ftel"
              class="input-width"
            />
          </el-form-item>
          <el-form-item :label="$t('market.ffax')" prop="ffax">
            <el-input
              v-model="administration.ffax"
              class="input-width"
            />
          </el-form-item>
          <el-form-item :label="$t('market.taxregistercode')" prop="ftaxregistercode">
            <el-input
              v-model="administration.ftaxregistercode"
              class="input-width"
            />
          </el-form-item>
          <el-form-item :label="$t('market.companyclassify')" prop="fcompanyclassifyName">
            <el-autocomplete
              v-model.trim="administration.fcompanyclassifyName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch18"
              size="mini"
              :popper-append-to-body="false"
              @focus="getBasicUnit('SX_COMPANYTYPE')"
              @select="selUnit"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="cliUnit('SX_COMPANYTYPE')"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.companynature')" prop="fcompanynatureName">
            <el-autocomplete
              v-model.trim="administration.fcompanynatureName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch18"
              size="mini"
              :popper-append-to-body="false"
              @focus="getBasicUnit('SX_COMPANYNATURE')"
              @select="selUnit"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="cliUnit('SX_COMPANYNATURE')"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.companyscale')" prop="fcompanyscaleName">
            <el-autocomplete
              v-model.trim="administration.fcompanyscaleName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch18"
              size="mini"
              :popper-append-to-body="false"
              @focus="getBasicUnit('SX_COMPANYSCALE')"
              @select="selUnit"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="cliUnit('SX_COMPANYSCALE')"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-form>
        <el-form
          ref="customerRef"
          label-width="100px"
          size="mini"
          :model="relevant"
          class="spacing"
          :rules="relevantRules"
        >
          <el-form-item :label="$t('market.custType')" prop="fcustTypeId">
            <el-autocomplete
              v-model.trim="relevant.fcustType"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch18"
              size="mini"
              :popper-append-to-body="false"
              @focus="getBasicUnit('SX_CUSTCATEGORY')"
              @select="selUnit"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="cliUnit('SX_CUSTCATEGORY')"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.custGroup')" prop="fgroup">
            <el-input
              v-model="relevant.fgroupName"
              class="input-width"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="handleGroup"
              />
            </el-input>
          </el-form-item>
          <!--          <el-form-item label="对应组织" prop="fcorrespondorgid">-->
          <!--            <el-select v-model="relevant.fcorrespondorgid" class="input-width">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item :label="$t('market.supplier')" prop="fsupplier">
            <el-input
              v-model="relevant.fsupplier"
              class="input-width"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="supplierVisiblit=true"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.note')" prop="fdescription" style="height: 50px;">
            <el-input
              v-model="relevant.fdescription"
              class="input-width"
              type="textarea"
            >
              <i slot="suffix" class="el-input__icon el-icon-search" />
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <jc-title :title1="$t('market.linkman')" />
      <jc-contacts ref="contactsRef" :contacts-value="contactsValue" />
      <jc-title :title1="$t('market.businessInfo')" />
      <jc-business ref="businessRef" :business.sync="business" />
      <jc-title :title1="$t('market.bankInfo')" :division="false" />
      <jc-bank :table-bank-data.sync="tableBankData" />
    </div>
    <!--客户分组-->
    <el-dialog
      v-dialogDrag
      class="dialog-class"
      :title="$t('market.custGroup')"
      model
      :visible.sync="openCustomer"
      :close-on-click-modal="false"
      width="500px"
    >
      <div class="public-form">
        <el-tree
          :data="relevant.fgroupArray"
          :props="defaultProps"
          @node-click="handleNodeClick"
        />
      </div>
    </el-dialog>
    <!--    国家-->
    <country v-if="openCountry" @country="countrySelectRow" />
    <!--供应商-->
    <supplier v-if="supplierVisiblit" @supplier="supplierData" />
    <!--  数据字典弹窗  -->
    <unit v-if="unitVisabled" :msg="funit" @unit="selUnit" />
  </div>
</template>

<script>
import jcTitle from '@/components/Title'
import JcBank from '@/views/market/customer/createCustomer/bank'
import JcBusiness from '@/views/market/customer/createCustomer/business'
import JcContacts from '@/views/market/customer/createCustomer/contacts'
import searData from '@/components/Search/mixin'
import {
  // 客户分组
  queryCustomerGroup,
  insertCustomer
} from '@/api/marketManage/customer/createCustomer'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import bility from '@/mixin/Operability'

export default {
  name: 'CreateCustomer',
  components: {
    jcTitle,
    JcBank,
    JcBusiness,
    JcContacts,
    supplier: () => import('@/views/purchasing/purchase/treePurchasePrice/component/supplier'),
    unit: () => import('@/views/basic/createMateriel2/components/unit'),
    country: () => import('@/views/purchasing/supplier/createSupplier/components/country')
  },
  mixins: [searData, autocomplete, bility],

  data() {
    return {
      funit: '',
      unitVisabled: false,
      supplierVisiblit: false,
      activeName: 'customer', // 默认基本信息
      ftype: 2052,
      fbillNo: 'fname', // 编码
      // 头部信息
      organization: {
        fname: '', // 客户名称
        fcode: '' // 客户编码
      },
      treeClickCount: 0, // tree点击次数
      // 基础数据
      basic: {
        fcountry: '', // 国家
        fcountryName: '', // 国家名称
        faddress: '', // 通讯地址
        fwebsite: '' // 公司网站
      },
      administration: {
        ftel: '', // 联系电话
        ffax: '', // 传真
        ftaxregistercode: '', // 纳税登记号
        fcompanyclassify: '', // 公司类别
        fcompanyclassifyName: '', // 公司类别名称
        fcompanynature: '', // 公司性质
        fcompanynatureName: '', // 公司性质名称
        fcompanyscale: '', // 公司规模
        fcompanyscaleName: '' // 公司规模名称
      },
      relevant: {
        fsupplier: '',
        fcorrespondorgid: '', // 对应组织
        fcustType: '', // 客户类别
        fcustTypeId: '', // 客户类别id
        fgroup: '', // 客户分组id
        fgroupName: '', // 客户名称
        fgroupArray: [], // 客户分组
        fdescription: '' // 备注
      },
      // 联系人
      contactsValue: {
        fcontacts: '', // 联系人
        ftels: '', // 公司电话
        fmailbox: '', // 联系人邮箱
        flegalContacts: '', // 法人
        flegalTels: '', // 法人电话
        flegalMailbox: '', // 法人邮箱
        fbusinessContacts: '', // 业务联系人
        fbusinessTels: '', // 业务电话
        fbusinessMailbox: '', // 业务邮箱
        ffinanceContacts: '', // 财务联系人
        ffinanceTels: '', // 财务电话
        ffinanceMailbox: '', // 财务邮箱
        coopeartiondate: new Date()
      },
      // 商务信息
      business: {
        ftradingCurr: '', // 结算币别
        ftradingCurrId: '', // 结算币别id  1
        fsaldept: '', // 销售部门
        fsaldeptId: '', // 销售部门id
        fsalgroup: '', // 销售组
        fsalgroupId: '', // 销售组id
        fseller: '', // 销售员
        fsellerId: '', // 销售员id
        fsettleType: '', // 结算方式
        fsettleTypeId: '', // 结算方式id  1
        freccondiTion: '', // 收款条件
        freccondiTionId: '', // 收款条件id  1
        fpricelistid: '', // 价目表
        fdiscountlist: 0, // 折扣率
        ftransleadTime: '', // 运输提前期
        ftaxType: '', // 税分类  1
        ftaxTypeArray: [], // 税分类数据
        finvoiceTypeArray: [], // 发票类型数据
        finvoiceType: '', // 发票类型   1
        ftaxRateName: '', // 默认税率名称
        ftaxRate: '' // 默认税率  1
      },
      tableBankData: [
        {
          fcountry: '', // 开户行国家
          fbankcode: '', // 银行账号
          fcurrencyId: '', // 币别id
          fcurrency: '', // 币别
          faccountName: '' // 账户名称
        }
      ],
      openCountry: false, // 国家
      openCustomer: false, // 客户分组
      total: 0, // 总条目
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      tableCountryData: [], // 国家数据
      basicRules: {
        fcountry: [
          {
            required: true,
            message: '请选择国家',
            trigger: 'blur'
          }
        ],
        fcityName: [
          {
            required: true,
            message: '请选择城市',
            trigger: 'blur'
          }
        ]
      },
      nameRules: {
        fname: [{ required: true, message: '请输入客户名称', trigger: 'blur' }]
      },
      adminRules: {
        ftel: [{ required: true, message: '请输入公司电话', trigger: 'blur' }]
      },
      relevantRules: {
        fcustTypeId: [
          {
            required: true,
            message: '请选择客户类别',
            trigger: 'change'
          }
        ],
        fgroup: [
          {
            required: true,
            message: '请选择客户分组',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    // 表单基础验证公用函数
    validationRules(refRules) {
      let value = null
      refRules(valid => {
        if (valid) {
          value = true
        } else {
          value = false
        }
      })
      return value
    },
    // 提交
    submit() {
      // 组织客户名称
      const name = this.validationRules(this.$refs.nameRef.validate)
      // 公司电话
      const contactsId = this.$refs.contactsRef.handleContactRef()
      // 商务信息
      const business = this.$refs.businessRef.handleBusinessRef()
      // 国家必选
      const countryId = this.validationRules(this.$refs.basicRef.validate)
      // 公司电话必选
      const callId = this.validationRules(this.$refs.callRef.validate)
      // 客户类别和客户分组必选
      const customerId = this.validationRules(this.$refs.customerRef.validate)
      if (
        !countryId ||
        !customerId ||
        !callId ||
        !business ||
        !contactsId ||
        !name
      ) {
        return
      }
      for (const item of this.tableBankData) {
        const result = Object.values(item).includes('')
        if (result) {
          this.$message.warning('银行信息不能为空！')
          return
        }
      }
      // 组织
      const { fname } = this.organization
      // 公司第一列
      const {
        fcountry, // 国家
        fprovincial, // 区县
        fprovince, // 省份
        fcity, // 城市
        fcityName: fcityString, // 城市名称
        faddress, // 通讯地址
        fwebsite // 公司网站
      } = this.basic
      const {
        ftel, // 联系电话
        ffax, // 传真
        ftaxregistercode, // 纳税登记号
        fcompanyclassify, // 公司类别
        fcompanynature, // 公司性质
        fcompanyscale // 公司规模
      } = this.administration
      const {
        fsupplier,
        fsupplierid,
        fcorrespondorgid,
        fcustTypeId, // 客户类别id
        fgroup, // 客户分组id
        fdescription // 备注
      } = this.relevant
      const {
        ftradingCurrId, // 结算币别id  1
        fsaldeptId, // 销售部门id
        fsalgroupId, // 销售组id
        fsellerId, // 销售员id
        fsettleTypeId, // 结算方式id  1
        freccondiTionId, // 收款条件id  1
        fpricelistid, // 价目表
        fdiscountlist, // 折扣表
        ftransleadTime, // 运输提前期
        ftaxType, // 税分类  1
        finvoiceType, // 发票类型   1
        ftaxRate // 默认税率  1
      } = this.business
      const data = {
        fsupplier,
        fsupplierid,
        fcorrespondorgid,
        fdocumentStatus: 'A',
        fname,
        // 公司第一列
        fcountry,
        fprovincial,
        fprovince,
        fcity,
        fcityString,
        faddress,
        fwebsite,
        ftel, // 联系电话
        ffax, // 传真
        ftaxregistercode, // 纳税登记号
        fcompanyclassify, // 公司类别
        fcompanynature, // 公司性质
        fcompanyscale, // 公司规模
        fcustTypeId, // 客户类别id
        fgroup, // 客户分组id
        fdescription, // 备注
        ftradingCurrId, // 结算币别id  1
        fsaldeptId, // 销售部门id
        fsalgroupId, // 销售组id
        fsellerId, // 销售员id
        fsettleTypeId, // 结算方式id  1
        freccondiTionId, // 收款条件id  1
        fpricelistid, // 价目表
        fdiscountlist, // 折扣表
        ftransleadTime, // 运输提前期
        ftaxType, // 税分类  1
        finvoiceType, // 发票类型   1
        ftaxRate, // 默认税率  1
        // 表格
        custBank: this.tableBankData
      }
      Object.assign(data, this.contactsValue)
      insertCustomer(data).then(res => {
        if (res.code !== 0) {
          this.$message({ showClose: true, message: res.message, type: 'error' })
          return
        }
        this.$store.dispatch('tagsView/guanbi', this.$route)
        // 跳转到修改页面
        this.$router.push({ path: `/editCustomer/${res.data}` })
        this.$message({ showClose: true, message: res.message, type: 'success' })
      })
    },
    // 获取供应商
    supplierData(ev) {
      if (ev.fsupplierId) {
        this.relevant.fsupplierid = ev.fsupplierId
        this.relevant.fsupplier = ev.fname
      }
      this.supplierVisiblit = false
    },
    // 打开客户分组
    async handleGroup() {
      this.openCustomer = true
      const { data: res } = await queryCustomerGroup()
      this.relevant.fgroupArray = res
    },
    // 客户分组
    handleNodeClick(item) {
      this.treeClickCount++
      if (this.treeClickCount >= 2) return
      this.timer = window.setTimeout(() => {
        if (this.treeClickCount === 1) {
          this.treeClickCount = 0
        } else if (this.treeClickCount > 1) {
          this.treeClickCount = 0
          const { value, label } = item
          this.relevant.fgroup = value
          this.relevant.fgroupName = label
          this.openCustomer = false
        }
      }, 300)
    },
    // 国家选中
    countrySelectRow(ev) {
      if (ev.fcountry) {
        const basic = this.basic
        basic.fcountryName = ev.fcountryname
        basic.fcountry = ev.fcountry
      }
      this.openCountry = false
    },
    // 数据字典弹窗
    cliUnit(ev) {
      this.funit = ev
      this.unitVisabled = true
    },
    // 数据字典选中
    selUnit(ev) {
      if (ev.fid) {
        if (this.funit === 'SX_COMPANYTYPE') { // 公司类型
          this.administration.fcompanyclassifyName = ev.fname
          this.administration.fcompanyclassify = ev.fid
        } else if (this.funit === 'SX_COMPANYNATURE') { // 公司性质
          this.administration.fcompanynatureName = ev.fname
          this.administration.fcompanynature = ev.fid
        } else if (this.funit === 'SX_COMPANYSCALE') { // 公司规模
          this.administration.fcompanyscaleName = ev.fname
          this.administration.fcompanyscale = ev.fid
        } else if (this.funit === 'SX_CUSTCATEGORY') { // 客户类别
          this.relevant.fcustType = ev.fname
          this.relevant.fcustTypeId = ev.fid
        }
      }
      this.unitVisabled = false
    },
    // 关闭弹窗事件
    closeDialog() {
      this.openCountry = false
      Object.keys(this.searCollData).forEach(key => {
        this.searCollData[key] = ''
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'src/styles/customer/inedx';
.content {
  @include listBom;
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form-item {
    height: 35px;
    margin-bottom: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 0;
  }
}
</style>
